<?php

namespace App\Models;

use Arcanedev\Support\Bases\Model;
use App\Models\Access\User\User;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Support\Facades\DB;
use Illuminate\Database\Eloquent\SoftDeletes;

class App extends Model
{
    use SoftDeletes;
    protected $table = 'app';
    protected $fillable = ['ogz_id','name','description','user_id','uet','type','is_foreign','etv','address','ops','msv','lvv','ut'];
    protected $primaryKey = 'id';

    public $timestamps = true;
    protected $dates = ['delete_at'];
    //机构app一对多
    public function belongsToOgz(){
        return $this->belongsTo(\App\Models\Ogz::class,'ogz_id','id');
    }
    //app和内容一对多
    public function hasManyVlus(){
        return $this->hasMany('App\Models\Flaw\Vuls','','id');
    }

    //类型
    const TYPEDEFAULT= 0;
    const CORE   = 1;
    const IMPORT = 2;
    const COMMON = 3;
    public static $type = [self::TYPEDEFAULT => '',self::CORE => '核心应用',self::IMPORT=>'重要应用',self::COMMON=>'一般应用'];

    //是否对外
    const FOREIGNDEFAULT = 0;
    const ONLYIN = 1;
    const ONLYOUT= 2;
    const INOUT  = 3;
    public static $is_foreign = [self::FOREIGNDEFAULT => '',self::ONLYIN=>'只对内',self::ONLYOUT=>'只对外',self::INOUT=>'内外都有'];

    /**
     * 列表信息
     * @param string $field
     * @param array $where
     * @param bool $getCount
     * @return mixed
     */
    public static function getList($field='*',$where=null,$getCount=false,$limit=[0,1000000]){
        $builder = DB::table('app as a')
            ->select($field)
            ->leftJoin('users as u','a.user_id','=','u.id')
            ->leftJoin('ogz as o','a.ogz_id','=','o.id');
        //独立查询
        $iddQuery = true;
        if ($where && is_array($where)){
            if (isset($where[0]) && $where[0]) {
                if ($where[0][1] == '!=') {
                    $builder = $builder->whereNotNull($where[0][0]);
                }
                if ($where[0][1] == '==') {
                    $builder = $builder->whereNull($where[0][0]);
                }
                //分组查询
                if (isset($where[1]) && $where[1]) {
                    $iddQuery = false;
                    $builder = $builder->where(function ($query) use ($where) {
                        $query->where($where[1][0][0], $where[1][0][1], $where[1][0][2])->orWhere($where[1][1][0], $where[1][1][1], $where[1][1][2]);
                    });
                }
            }
            if (isset($where[1]) && $where[1] && $iddQuery) {
                $builder = $builder->where($where[1][0][0], $where[1][0][1], $where[1][0][2]);
                //循环构建器
                $_depth = self::array_depth($where[1]);
                for ($i = 1; $i < $_depth; $i++) {
                    $builder = $builder->orwhere($where[1][$i][0], $where[1][$i][1], $where[1][$i][2]);
                }
            }
        }
        //全局条件
        if (isset($where[2]) && $where[2])
            $builder = $builder->whereIn($where[2][0],$where[2][1]);
        if ($getCount){
            return $builder->count();
        } else {

            return $builder->offset($limit[0])->limit($limit[1])->orderBy('a.created_at','DESC')->orderBy('a.sort','DESC')->get();

        }

    }

    /**
     * 数组维度
     * @param $array
     * @return int
     */
    private static function array_depth($arry) {
        if(!is_array($arry)) return 0;
        $max_depth = 1;
        foreach ($arry as $value) {
            if (is_array($value)) {
                //递归深度
                $depth = self::array_depth($value) + 1;

                if ($depth > $max_depth) {
                    $max_depth = $depth;
                }
            }
        }
        return $max_depth;
    }
    /**
     * 插入记录
     * @param array $data
     * @return bool
     */
    public static function insertRow($data){

        if (empty($data))
            return false;

        return self::create($data);

    }

    /**
     * 修改记录
     * @param array $where
     * @param array $data
     * @return bool
     */
    public function updateRow($where,$data){

        if (empty($data))
            return false;
        $arr = [];
        foreach ($this->fillable as $filed){
            $arr[$filed] = $data[$filed];
        }
        return self::where($where[0],$where['1'])
            ->update($arr);

    }

    /**
     * 删除记录
     * @param array $where
     * @param array $data
     * @return bool
     */
    public function deleteRow($request){
        if (empty($request->id)){
            throw new \Exception('非法操作');
        }
        $app = $this->find($request->id);
        $app->delete();
        if ($app->trashed()) {
            return true;
        }else{

            throw new \Exception('企业应用禁用失败');
        }
        /*if ($app->hasManyVlus()->count() > 0){
            throw new \Exception('有漏洞内容关联，请勿删除');
        }
        if ($app->delete()) {
            return true;
        }else{

            throw new \Exception('应用删除失败');
        }*/

    }
    /**
     * 激活
     * @param mixed $request
     * @return bool
     */
    public static function activeRow($request){

        $app = App::withTrashed()->find($request->id);
        //避免禁用用户二次进入
        if ($app){
            $app->deleted_at = NULL;
            if ($app->save()){
                return true;
            }
        }
        return false;

    }
    /**
     * 根据机构查询
     * @param array $ogz_id
     * @return mixd
     */
    public static function getAppByOgzIds($ogz_ids,$withTrash = false){
        $buider = App::whereIn('ogz_id',$ogz_ids)->select('id');
        if ($withTrash){
            $buider = $buider->withTrashed();
        }
        return $buider->get()->toArray();
    }
    /**
     * 根据联系人查询用户
     * @param integer $Uid
     * @return mixd
     */
    public static function getAppByUser($Uid){
        $fields = ['id','name','description','sort'];
        //取消已禁用的数据
        $setWhere = 'find_in_set('.intval($Uid).',user_id) and deleted_at is NULL';
        $app = DB::table('app')->select($fields)->whereRaw($setWhere)->get();

        return $app;
    }

    /**
     * 获取一条指定列值
     * @param array $column
     * @param int $id
     * @return mixed
     */
    public static function getRowByColumn ($column,$id) {
        $ret = collect();
        if ($column && is_int($id)) {
            $ret = self::select(['id', 'name'])->where('ogz_id','=', $id)->get();
        }
        return $ret;
    }
    /**
     * 获取指定字段数据
     * @param array $field
     * @param array $where
     * @param bool $trash
     * @return array
     */
    public static function getCollectWithSel ($field,$where,$trash=false){
        $ret = [];
        if ($field && $where) {
            $builder = static::select($field);
            if ($trash) {
                $builder = $builder->onlyTrashed();
            }
            $ret = $builder->whereIn('id',access()->hasApps())->where($where)->get();
        }
        return $ret;
    }

    /**
     * 获取一条指定列值，指定时间范围
     * @param array $column
     * @param int $id
     * @param array $betweenTime
     * @return mixed
     */
    public static function getRowBetweenTime ($column,$id,$betweenTime) {
        $ret = collect();
        if ($column && is_int($id)) {
            $ret = self::select(['id', 'name'])->where('ogz_id','=', $id)->whereBetween('created_at',$betweenTime)->get();

        }
        return $ret;
    }

}
